package com.tansun.tandata.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.tansun.tandata.service.ApprovalService;
import com.tansun.tandata.vo.LdapUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tansun.tandata.entity.Role;
import com.tansun.tandata.entity.User;
import com.tansun.tandata.entity.UserRole;
import com.tansun.tandata.mapper.UserDao;
import com.tansun.tandata.service.UserService;
import com.tansun.tandata.utils.CodeGenerator;
import com.tansun.tandata.utils.Constants;
import com.tansun.tandata.utils.ParentServiceImp;
import com.tansun.tandata.vo.req.UserChangePwdVO;
import com.tansun.tandata.vo.req.UserVO;
import com.tansun.tandata.vo.res.UserInfoVO;
import com.tansun.tandata.vo.res.UserRoleByLoginNameVO;
import com.tansun.tandata.vo.res.UserRoleVO;
import com.tansun.tjmas.cloud.base.redis.utils.RedisUtils;

/**
 * @Description 用户信息业务类
 * @CreateDate 20200426
 * @author shenxiaodong
 * @Version v1.0
 *
 */

@Service("userServiceImpl")
public class UserServiceImpl extends ParentServiceImp<UserDao, User> implements UserService {
	
	@Autowired
	UserDao userDao;
    @Autowired
	ApprovalService approvalService;
	@Autowired
	private RedisUtils redisUtils;
	
	/**
     * @Description 验证名字是否存在
     */
    public int getUserByName(String name) {
    	return userDao.getUserByName(name);
    }

	/**
     * @Description 验证名字和电话是否存在
     */
    public int getUserByLoginNameOrPhone(String name,String phone) {
    	return userDao.getUserByLoginNameOrPhone(name, phone);
    }
    
    /**
     * @Description 根据用户id查询用户信息
     */
    public UserRoleVO selectUserById(String id) {
    	return userDao.selectUserById(id);
    }
    
    /**
     * 查询所有用户信息
     */
    public List<UserRoleVO> selectAllUser(){
    	return userDao.selectAllUser();
    }
    
    /**
     * 添加用户信息
     */
    public void saveUser(UserVO userVO){
        //用户属性赋值
        UserRoleVO user = new UserRoleVO();
        BeanUtils.copyProperties(userVO, user);
        user.setUserCode(CodeGenerator.getUUID(User.class));
        user.setCreater(getCurrUserId());
        Date date = new Date();
        user.setCreaterTime(date);
        user.setUpdateTime(date);
        user.setUpdater(getCurrUserId());
        user.setIsDelete(Constants.DELETE_FLAG_RESERVED);
        user.setStatus(Constants.USER_STATUS_ACTIVE);
        user.setUpdateCount(Constants.USER_UPDATE_COUNT_INIT);
        //给数据库的user_role添加用户和角色关联关系
        UserRole ur = new UserRole();
        ur.setUserCode(user.getUserCode());
        ur.setRoles(user.getRoles());
        //用户信息保存
        System.out.println("zhun bei bao cun yu zhang hu ******************");
        userDao.saveUser(user);
        System.out.println("bao cun cheng gong yu zhang  hu ******************"+user.getUserCode());
        if(ur.getUserCode()!=null&&ur.getRoles()!=null&&ur.getRoles().size()>0) {
            userDao.saveUserRole(ur);
        }
        //操作redis
        redisUtils.set(Constants.USER_REDIS + user.getUserCode(), user.getUserName());
        System.out.println("bao cun redise cheng gong ******************");
    }
    
    /**
     * 修改用户信息
     */
    public void updateUser(UserVO userVO) {
        //用户属性赋值
        UserRoleVO user = new UserRoleVO();
        BeanUtils.copyProperties(userVO, user);
        if (userVO.getNewPassword().equals("")){
            user.setPassword(userVO.getPassword());
        }else {
            user.setPassword(userVO.getNewPassword());
        }
        user.setUpdater(getCurrUserId());
        user.setUpdateTime(new Date());
        userDao.updateUser(user);
        if(user.getRoles()!=null) {
            userDao.deleteUserRole(user.getUserCode());
            UserRole ur = new UserRole();
            ur.setUserCode(user.getUserCode());
            ur.setRoles(user.getRoles());
            userDao.saveUserRole(ur);
        }
        //操作redis
        redisUtils.set(Constants.USER_REDIS + user.getUserCode(), user.getUserName());
    }
    
    /**
     * 删除用户信息
     */
    public void deleteUser(String userCode) {
        userDao.deleteUserRole(userCode);
    	userDao.deleteUserByUserId(userCode);
    	//操作redis
    	redisUtils.delete(Constants.USER_REDIS + userCode);
    }
    
    /**
     * 删除用户角色信息
     */
    public void deleteUserRole(String userCode) {
    	userDao.deleteUserRole(userCode);
    }
    
    /**
     * 根据用户编号修改用户类型 
     */
    @Transactional(readOnly = false)
    public void updateUserType(String userCode,String status) {
        Map<String, Object> params = new HashMap<>();
        params.put("userCode", userCode);
        params.put("status", status);
    	userDao.updateUserType(params);
    }
    
    /**
     * @Description 模糊查询用户信息
     */
    @Override
    public List<UserRoleVO> getUserByKey(String keywords, int status) {
    	return userDao.getUserByKey(keywords, status);
    }

    /**
     * 根据用户登录名称查询用户基本信息
     */
    public UserRoleByLoginNameVO selectUserAndRoleInfoByLoginName(String loginName) {
        UserRoleVO user;
        UserRoleByLoginNameVO userRoleByLoginNameVO = new UserRoleByLoginNameVO();
        UserInfoVO userInfoVO = new UserInfoVO();
        List<String> roleCodeList = new ArrayList<>();
        userRoleByLoginNameVO.setUserInfo(userInfoVO);
        userRoleByLoginNameVO.setRole("");
        //根据登录名查询用户信息和角色信息
        user = userDao.selectUserAndRoleInfoByLoginName(loginName);
        if (user != null){
           List<Role> addRoles= approvalService.authUserApprovalRole(user);
            userInfoVO.setUserCode(user.getUserCode());
            userInfoVO.setUserName(user.getUserName());
            userInfoVO.setLoginName(user.getLoginName());
            userInfoVO.setUserPhone(user.getUserPhone());
            userInfoVO.setPassword(user.getPassword());
            userInfoVO.setOrgCode(user.getOrgCode());
            userInfoVO.setType(user.getType());
            userInfoVO.setStatus(user.getStatus());
            List<Role> roles = user.getRoles();
            if(roles==null){
                roles = new ArrayList<>();
            }
            roles.addAll(addRoles);
            user.setRoles(roles);
                for (Role role : user.getRoles()) {
                    roleCodeList.add(role.getRoleCode());
                }
                userRoleByLoginNameVO.setRole(StringUtils.join(roleCodeList.toArray(), ","));
        }

	    return userRoleByLoginNameVO;
    }

    /**
     * 用户登录以后返回用户基本信息
     */
    public UserInfoVO getUserInfoAfterLogin(String loginName) {
        UserRoleVO user;
        UserInfoVO userInfoVO = new UserInfoVO();
        user = userDao.getUserInfoAfterLogin(loginName);
        if (user != null){
            userInfoVO.setUserCode(user.getUserCode());
            userInfoVO.setLoginName(user.getLoginName());
            userInfoVO.setUserName(user.getUserName());
            userInfoVO.setUserPhone(user.getUserPhone());
            userInfoVO.setPassword(user.getPassword());
            userInfoVO.setType(user.getType());
            userInfoVO.setStatus(user.getStatus());
        }
        return userInfoVO;
    }

    /**
     * 更新用户密码
     */
    @Override
    public void updateUserPwd(UserChangePwdVO userChangePwdVO) {
        //用户属性赋值
        UserRoleVO user = new UserRoleVO();
        user.setUserCode(userChangePwdVO.getUserCode());
        user.setPassword(userChangePwdVO.getNewPassword());
        user.setUpdateTime(new Date());
        user.setUpdater(getCurrUserId());
        userDao.updateUser(user);
    }

    /**
     * 修改用户对应的机构
     */
    public void updateOrgCodeByUser(String userCode, String orgCode) {
        Map<String, Object> params = new HashMap<>();
        params.put("userCode", userCode);
        params.put("orgCode", orgCode);
        userDao.updateOrgCodeByUser(params);
    }

    /**
     * 获取用户通过组织编码
     */
    @Override
    public int getUserByOrgCode(String orgCode) {
        return userDao.getUserByOrgCode(orgCode);
    }
    @Override
    public int ldapUserToSysUser(LdapUser ldapUser) {
        System.out.println("wo jin yu tong bu yu zhang hao fang fa le ******************");
       User user = userDao.findUserByName(ldapUser.getSAMAccountName());
       if(user==null){
           //新建用户
           UserVO userVO = new UserVO();
           userVO.setLoginName(ldapUser.getSAMAccountName());
           userVO.setPassword(ldapUser.getPassword());
           userVO.setUserName(ldapUser.getCn());
           userVO.setType("2");//域用户
           saveUser(userVO);
           return 1;
       }

       if(user.getStatus()==0&&"2".equals(user.getType())){
           //解锁域用户
           UserRoleVO userRoleVO = new UserRoleVO();
           userRoleVO.setUserCode(user.getUserCode());
           userRoleVO.setStatus(1);//解锁
           userDao.updateUser(userRoleVO);
       }
       if(user.getPassword().equals(ldapUser.getPassword())){
           //密码无变化
           return 1;
       }
        //更新密码
        UserChangePwdVO userChangePwdVO = new UserChangePwdVO();
        userChangePwdVO.setUserCode(user.getUserCode());
        userChangePwdVO.setOldPassword(user.getPassword());
        userChangePwdVO.setNewPassword(ldapUser.getPassword());
        updateUserPwd(userChangePwdVO);
        return 1;
    }

    @Override
    public int lockLdapUserByLoginName(String loginName) {
        User user = userDao.findUserByName(loginName);
        if(user!=null&&"2".equals(user.getType())){
            UserRoleVO userInfoVO = new UserRoleVO();
            userInfoVO.setUserCode(user.getUserCode());
            userInfoVO.setStatus(0);//冻结
            userDao.updateUser(userInfoVO);
        }
        return 1;
    }
}

